-- UIAwakeCarvingSelect
-- Create by chendh
-- 觉醒雕像选择界面

-- UIAwakeCarvingSelect继承自Layer
UIAwakeCarvingSelect = class("UIAwakeCarvingSelect", function()
    return cc.Layer:create();
end);

function UIAwakeCarvingSelect.create()
    return UIAwakeCarvingSelect.new();
end

-- 最大行数
local MAX_GRID_ROW    = 2;
local PAGE_COLUMN = 3;

-- 内部函数声明

-- 构造函数
function UIAwakeCarvingSelect:ctor(id)
    -- 初始化
    self:setName("UIAwakeCarvingSelect");
    local node = cc.CSLoader:createNode("layout/training/TrainingHeroSelect.csb");
    self:addChild(node);
    self.node = node;

    --self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    local CT = node:getChildByName("CT");
    local template = CT:getChildByName("template");
    local scrollview = template:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 垂直滑动，需要显示上下蒙版
    local mask1 = findChildByName(self.node, "CT/template/mask1");
    mask1:setVisible(true);
    local mask2 = findChildByName(self.node, "CT/template/mask2");
    mask2:setVisible(true);

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化格子
    self:initGrids(self.node);

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIAwakeCarvingSelect:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化数据
function UIAwakeCarvingSelect:initData()
    local result = {};
    local heroList = ME.user:getAllPetIds();

    for _, petId in ipairs(heroList) do
        if AwakeM.isFinishAwakeDungeon(petId) and
            not AwakeM.isCarved(petId) then
            table.insert(result, petId);
        end
    end

    table.sort(result, sortHero);
    return result;
end

-- 初始化格子
function UIAwakeCarvingSelect:initGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 10;

    -- 图标间距(纵向)
    local hGap = 40;

    -- 图标宽度
    local iconWidth = 140;

    -- 图片高度
    local iconHeight = 170;

    local topHGap  = 0;
    local bottomHGap  = 50;
    local leftWGap = 10;

    -- 收集信息
    local heroList = self:initData();
    self.heroList = heroList;
    -- 总数
    local totalCount = #self.heroList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/training/TrainingHeroItem.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, totalCount, MAX_GRID_ROW, PAGE_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerTrainItemTouchEvent);
end

local function sortHero(id1, id2)
    local canUpgrade1 = AwakeM.canCarving(id1);
    local canUpgrade2 = AwakeM.canCarving(id2);

    -- 可以升阶的在前面
    if canUpgrade1 == true and canUpgrade2 ~= true then
        return true;
    elseif canUpgrade1 ~= true and canUpgrade2 == true then
        return false;
    end

    -- 两个都不可以升阶
    local pet1 = PetM.getMyPet(id1);
    local pet2 = PetM.getMyPet(id2);

    local weaponClassId1 = EquipM.getHeroEquip(pet1, EQUIP_TYPE_WEAPON, 1) or 0;
    local medalClassId1 = EquipM.getHeroEquip(pet1, EQUIP_TYPE_MEDAL, 1) or 0;
    local weaponClassId2 = EquipM.getHeroEquip(pet2, EQUIP_TYPE_WEAPON, 1) or 0;
    local medalClassId2 = EquipM.getHeroEquip(pet2, EQUIP_TYPE_MEDAL, 1) or 0;

    local ret = PetM.getUpgradeRankEquip(pet1, EQUIP_TYPE_WEAPON);
    local hasWeaponNotEquip1 = (ItemM.haveItemOrCanCompound(ME.user, ret[1]) and weaponClassId1 == 0) or weaponClassId1 > 0;

    ret = PetM.getUpgradeRankEquip(pet1, EQUIP_TYPE_MEDAL);
    local hasMedalNotEquip1 = (ItemM.haveItemOrCanCompound(ME.user, ret[1]) and medalClassId1 == 0) or medalClassId1 > 0;

    ret = PetM.getUpgradeRankEquip(pet2, EQUIP_TYPE_WEAPON);
    local hasWeaponNotEquip2 = (ItemM.haveItemOrCanCompound(ME.user, ret[1]) and weaponClassId2 == 0) or weaponClassId2 > 0;

    ret = PetM.getUpgradeRankEquip(pet2, EQUIP_TYPE_MEDAL);
    local hasMedalNotEquip2 = (ItemM.haveItemOrCanCompound(ME.user, ret[1]) and medalClassId2 == 0) or medalClassId2 > 0;

    -- 武器和证书的合成材料足够，但至少有一件未装备的排前面
    if (hasWeaponNotEquip1 and hasMedalNotEquip1) and not (hasWeaponNotEquip2 and hasMedalNotEquip2) then
        return true;
    elseif (hasWeaponNotEquip2 and hasMedalNotEquip2) and not (hasWeaponNotEquip1 and hasMedalNotEquip1) then
        return false;
    end

    -- 剩余的，按星级低到高排列
    local rank1 = pet1:getRank();
    local rank2 = pet2:getRank();
    if rank1 < rank2 then
        return true;
    elseif rank1 > rank2 then
        return false;
    end

    return id1 > id2;

end

-- 显示英雄选择界面
function UIAwakeCarvingSelect:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.node, "CT/template/title");
    titleLabel:setString(getLocStr("slime_album"));
    TextStyleM.setTitleStyle(titleLabel);

    -- 收集信息
    local heroList = self.heroList;

    local totalGridCount = #heroList;

    if not heroList or #heroList == 0 then
        cclog("收集英雄信息失败。");

        local text = ccui.Text:create();
        --text:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);
        TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_GRAY);
        text:setString(getLocStr("not_qualified_pet"));
        local CTNode = findChildByName(self.node, "CT");
        CTNode:addChild(text);
        return;
    end

    -- 显示信息
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            --  初始化格子信息
            self:initGridInfo(grid, heroList[i]);
        end
    end
end

-- 重绘英雄星级
function UIAwakeCarvingSelect:redrawHeroStar(starNode, classId)
    local hero = PetM.getMyPet(classId);
    if not hero then
        return;
    end

    -- 获取英雄阶位
    local starNum = hero:getRank();
    local maxStarNum = starNum;

    -- 生成星星层，直接挂到结点上
    local lightStarPath = "images/ui/symbol/star_little.png";
    local darkStarPath  = "images/ui/symbol/star_little2.png";
    local layer = createStarLayerEx(starNum, maxStarNum, lightStarPath, darkStarPath, "center", -0.7);
    if not layer then
        return;
    end
    starNode:removeAllChildren();
    starNode:addChild(layer);
end

--  初始化格子信息
function UIAwakeCarvingSelect:initGridInfo(grid, id)
    local pet = PetM.getMyPet(id);

    local panel = findChildByName(grid, "panel");
    panel.petId = id;

    local weaponBg = findChildByName(grid, "tab1");
    weaponBg.petId = id;

    local medalBg = findChildByName(grid, "tab2");
    medalBg.petId = id;

    local weaponImg = findChildByName(grid, "weapon");
    local medalImg = findChildByName(grid, "medal");
    local icon = findChildByName(grid, "icon");
    local activeTip = findChildByName(grid, "active_tip");
    local activeText = findChildByName(grid, "activated");
    local starNode = findChildByName(grid, "star_node");

    local bg = findChildByName(grid, "bg");

    -- 英雄头像
    local fileName = pet:getIcon();
    local iconPath = getHeroIconPath(fileName);
    icon:loadTexture(iconPath);

    if AwakeM.canCarving(pet.classId) ~= true then
        -- 无法升阶时，背景变透明
        icon:setOpacity(125.5);
        bg:setOpacity(100);
        weaponBg:setOpacity(125.5);
        medalBg:setOpacity(125.5);
    else
        icon:setOpacity(255);
        bg:setOpacity(255);
        weaponBg:setOpacity(255);
        medalBg:setOpacity(255);
    end

    -- 是否出战中，或处于灵魂链接状态
    local activePet = ME.user.dbase:query("active_pet");
    if PetM.isActivePet(pet.classId) or
        (PetM.isLictorPet(pet.classId) and IsInTable(pet.classId, CampM.getCampPets(activePet)) and DungeonM.isPause()) then
        activeTip:setVisible(true);
        if PetM.isLictorPet(pet.classId) then
            activeTip:loadTexture(getCornerImg("linked"));
        else
            activeTip:loadTexture(getCornerImg("risking"));
        end

        activeText:setVisible(false);
        TextStyleM.setTextStyle(activeText, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
        activeText:setString(getLocStr("pet_is_advanture"));
    else
        activeTip:setVisible(false);
        activeText:setVisible(false);
    end

    -- 初始化星级
    self:redrawHeroStar(starNode, pet.classId);

    -- 武器
    weaponImg:loadTexture("images/ui/hero/add.png");
    weaponImg:setVisible(true);
    weaponImg:stopAllActions();
    local weaponClassId = EquipM.getHeroEquip(pet, EQUIP_TYPE_WEAPON, 1);
    if weaponClassId then
        weaponBg.itemId = weaponClassId;
        local iconIndex = ItemM.query(weaponClassId, "icon");

        if haveItemSmallIcon(iconIndex) then
            weaponImg:loadTexture(getItemSmallIconPath(iconIndex));
            weaponImg:setScale(0.95);
        else
            weaponImg:loadTexture(getItemIconPath(iconIndex));
            weaponImg:setScale(0.4);
        end

        if AwakeM.canCarving(pet.classId) ~= true then
            weaponImg:setOpacity(125.5);
        else
            weaponImg:setOpacity(255);
        end
    else
        weaponBg.itemId = nil;
        weaponImg:setScale(0.95);
        weaponImg:setOpacity(255);

        local ret = PetM.getUpgradeRankEquip(pet, EQUIP_TYPE_WEAPON);
        weaponClassId = ret[1];
        if not ItemM.haveItemOrCanCompound(ME.user, weaponClassId) then
            weaponImg:setVisible(false);
        else
            local scale = weaponImg:getScale();
            local action = cc.Sequence:create(cc.ScaleTo:create(0.5, 1.1 * scale), cc.ScaleTo:create(0.5, 1 * scale));
            weaponImg:runAction(cc.RepeatForever:create(action));
        end
    end

    -- 徽章
    medalImg:loadTexture("images/ui/hero/add.png");
    medalImg:setVisible(true);
    medalImg:stopAllActions();
    local medalClassId = EquipM.getHeroEquip(pet, EQUIP_TYPE_MEDAL, 1);
    if medalClassId then
        local iconIndex = ItemM.query(medalClassId, "icon");
        medalBg.itemId = medalClassId;

        if haveItemSmallIcon(iconIndex) then
            medalImg:loadTexture(getItemSmallIconPath(iconIndex));
            medalImg:setScale(1);
        else
            medalImg:loadTexture(getItemIconPath(iconIndex));
            medalImg:setScale(0.4);
        end
        if AwakeM.canCarving(pet.classId) ~= true then
            medalImg:setOpacity(125.5);
        else
            medalImg:setOpacity(255);
        end
    else
        medalBg.itemId = nil;
        medalImg:setScale(1);
        medalImg:setOpacity(255);

        local ret = PetM.getUpgradeRankEquip(pet, EQUIP_TYPE_MEDAL);
        medalClassId = ret[1];
        if not ItemM.haveItemOrCanCompound(ME.user, medalClassId) then
            medalImg:setVisible(false);
        else
            local scale = medalImg:getScale();
            local action = cc.Sequence:create(cc.ScaleTo:create(0.5, 1.1 * scale), cc.ScaleTo:create(0.5, 1 * scale));
            medalImg:runAction(cc.RepeatForever:create(action));
        end
    end
end

-- 注册商品点击事件
function UIAwakeCarvingSelect:registerTrainItemTouchEvent(node)
    -- 打开详情界面
    local function showHeroDetailInfo(id)
        self.isLongPress = true;

        -- 打开冈布奥详细信息界面
        require "game/ui/form/hero/UIHeroDetailInfo"
        local uiForm = UIHeroDetailInfo.create(id);
        UIMgr.getCurrentScene():addForm(uiForm);
    end

    -- 注册商品图标点击事件
    local bgBtn = node:getChildByName("bg");
    local oldScale = node:getScale();
    local panel = findChildByName(node, "panel");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            node:setScale(0.95 * oldScale);
        elseif eventType == ccui.TouchEventType.ended then
            node:setScale(oldScale);
            local ret = AwakeM.canCarving(panel.petId);
            if ret ~= true then
                return alert(getLocStr(ret));
            end

            -- 关闭本界面
            -- UIMgr.getCurrentScene():removeFormByName("UIAwakeCarvingSelect");

            -- 已选定，打开雕刻确认界面
            require "game/ui/form/awake/UIAwakeCarvingConfirm"
            local uiForm = UIAwakeCarvingConfirm.create(panel.petId);
            UIMgr.getCurrentScene():addForm(uiForm);
            AudioM.playFx("ui_open1");
        end
    end
    bgBtn:addTouchEventListener(onClick)

    -- 武器点击回调
    local weaponBg = findChildByName(node, "tab1");
    local function OnWeaponCompoundClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            if sender.itemId then

            else
                local pet = PetM.getMyPet(sender.petId);

                local info = {};
                info.pet = pet;
                info.type = EQUIP_TYPE_WEAPON;

                -- 如果获取不到升阶所需的武器或者所需武器的阶位为1，则不显示合成界面
                local ret = PetM.getUpgradeRankEquip(pet, EQUIP_TYPE_WEAPON);
                if UIHeroMain.equipWeapons(nil, pet, ret[1], EQUIP_TYPE_WEAPON) then
                    return;
                end

                if ItemM.haveItemOrCanCompound(ME.user, ret[1]) then
                    -- 出战和链接的不允许佩戴
                    if PetM.pauseDungeonLimit(sender.petId) then
                        if PetM.isActivePet(sender.petId) then
                            alert(getLocStr("active_no_weapon"));
                        else
                            alert(getLocStr("lictor_no_weapon"));
                        end
                        return;
                    end

                    -- 显示合成界面
                    require "game/ui/form/item/UIItemCompound"
                    UIMgr.getCurrentScene():removeFormByName("UIItemCompound");
                    local UIItemCompound = UIItemCompound.create(sender.petId, ret[1]);
                    UIMgr.getCurrentScene():addForm(UIItemCompound);
                end
            end
        end
    end
    weaponBg:addTouchEventListener(OnWeaponCompoundClick)

    -- 徽章点击回调
    local medalBg = findChildByName(node, "tab2");
    local function onMedalClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            if sender.itemId then

            else
                local pet = PetM.getMyPet(sender.petId);
                local info = {};
                info.pet = pet;
                info.type = EQUIP_TYPE_MEDAL;

                local ret = PetM.getUpgradeRankEquip(pet, EQUIP_TYPE_MEDAL);
                if UIHeroMain.equipWeapons(nil, pet, ret[1], EQUIP_TYPE_MEDAL) then
                    return;
                end

                -- 显示合成界面
                if ItemM.haveItemOrCanCompound(ME.user, ret[1]) then
                    -- 出战和链接的不允许佩戴
                    if PetM.pauseDungeonLimit(sender.petId) then
                        if PetM.isActivePet(sender.petId) then
                            alert(getLocStr("active_no_medal"));
                        else
                            alert(getLocStr("lictor_no_medal"));
                        end
                        return;
                    end

                    require "game/ui/form/item/UIItemCompound"
                    UIMgr.getCurrentScene():removeFormByName("UIItemCompound");
                    local UIItemCompound = UIItemCompound.create(sender.petId, ret[1]);
                    UIMgr.getCurrentScene():addForm(UIItemCompound);
                end
            end
        end
    end
    medalBg:addTouchEventListener(onMedalClick);
end

-- 注册事件处理回调函数
function UIAwakeCarvingSelect:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UIAwakeCarvingSelect");
        elseif eventType == "enter" then

        end
    end);

    -- 注册英雄穿上装备的回调
    EventMgr.register("UIAwakeCarvingSelect", event.EQUIP, function(args)
        self:redraw();
    end);

    -- 注册英雄升阶的回调
    EventMgr.register("UIAwakeCarvingSelect", event.AWAKE_CARVING_START, function(args)
        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UIAwakeCarvingSelect");
    end)
end

-- 注册点击事件
function UIAwakeCarvingSelect:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIAwakeCarvingSelect");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

